﻿/*
(c) 2010 - Open Source Business Foundation e. V. (www.osbf.de)
This software is provided under Microsoft Reciprocal License (Ms-RL)
(http://www.microsoft.com/opensource/licenses.mspx#Ms-RL)
All other rights reserved
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace MicroFormatProcessing
{
    /// <summary>
    /// This class is doing the Queries for the Tags
    /// </summary>

    public class TagRepository
    {
        private static CloudStorageAccount storageAccount;
        private TagContext context;

        static TagRepository()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSetter) =>
           configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));
            storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist(TagContext.TABLE_NAME);
            // CloudTableClient.CreateTablesFromModel(typeof(MfUserTagContext), storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
        }

        public TagRepository()
        {
            this.context = new TagContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
            this.context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
            this.context.IgnoreResourceNotFoundException = true;
        }

        public List<Tag> FindByUserId(string userId)
        {
            return FindByUserIdAndTagName(userId, null);
        }

        public List<Tag> FindByUserIdAndTagName(string userId, string tagName)
        {
            List<Tag> result = new List<Tag>();
            if (this.context.Tags.FirstOrDefault() != null)
            {
                CloudTableQuery<Tag> query;
                if (tagName != null)
                {
                    query = (from t in this.context.Tags where t.PartitionKey == userId && t.RowKey == tagName select t).AsTableServiceQuery<Tag>();
                }
                else
                {
                    query = (from t in this.context.Tags where t.PartitionKey == userId select t).AsTableServiceQuery<Tag>();
                }
                foreach (Tag tag in query.Execute())
                {
                    tag.DeSerializeAttributes();
                    result.Add(tag);
                }
            }
            return result;
        }

        public void Add(Tag tag)
        {
            if (tag != null)
            {
                tag.SerializeAttributes();
                this.context.Add(tag);
                this.context.SaveChanges();
            }
        }

        public void Update(Tag tag, bool attach)
        {
            if (tag != null)
            {
                tag.SerializeAttributes();
                if (attach)
                {
                    this.context.AttachTo(tag);
                }
                this.context.Update(tag);
                this.context.SaveChanges();
            }
        }

        public void Delete(Tag tag, bool attach)
        {
            if (tag != null)
            {
                tag.SerializeAttributes();
                if (attach)
                {
                    this.context.AttachTo(tag);
                }
                this.context.Delete(tag);
                this.context.SaveChanges();
            }
        }
    }
}